import React, { Component, useMemo } from 'react'
import { View } from '@tarojs/components'
import Taro, { getCurrentInstance } from '@tarojs/taro'
import { timestampToTime, transformData } from '@/utils'
import { SpNavBar } from '@/components'
import api from '@/api'
import './index.scss'
import { connect } from 'react-redux'
import {
    Form,
    Input,
    Button,
    Dialog,
    TextArea,
    DatePicker,
    CascadePicker,
    Stepper,
    Switch,
    Checkbox,
    Space,
    Radio,
    Selector,
    Picker,
    Popup,
    SearchBar,
    CheckList
} from 'antd-mobile'
import dayjs from 'dayjs'
import {
    TAG_MAP,
    SELECCAT_MAP,
    BRAND_MAP2,
    GOOD_MAP
} from '../../good/const'
import GoodsCheck from './comps/goodsCheck'
import { values } from 'lodash'


const COUPON_TYPE = {
    'discount': '折扣券',
    'cash': '满减券',
    'new_gift': '兑换券'
}

@connect(({ planSelection }) => ({
    planSelection: planSelection.activeShop
}))
export default class List extends Component {
    formRef = React.createRef()

    constructor(props) {
        super(props)
        this.state = {
            couponStr: '',
            totalDays: [],
            visible: false,
            visible1: false,
            visible2: false,
            selected: 'A',
            searchText: '',
            mainCategoryList: [],
            categoryList: [],
            brandList: [],
            goodsList: [],
            form: {
                color: '#000000',
                card_id: '',
                card_type: 'discount',
                title: '',
                least_cost: 0,
                reduce_cost: '',
                discount: '',
                gift: '',
                quantity: '',
                date_type: 'DATE_TYPE_FIX_TIME_RANGE',
                begin_time: 0,
                days: 30,
                end_time: '',
                time_limit_date: [],
                get_limit: 1,
                use_all_shops: 'true',
                rel_shops_ids: [],
                distributor_id: [],
                text_image_list: [],
                receive: true,
                store_self: false,
                use_scenes: 'ONLINE',
                if_push_wechat: false,
                useCondition: 2,
                self_consume_code: 0,
                use_platform: 'store',
                rel_item_ids: [],
                use_all_items: 'true',
                most_cost: 999999,
                item_category: [],
                tag_ids: [],
                brand_ids: [],
                items: [],
            },
        }
    }
    async componentWillUnmount() {
        console.log('2222')

    }
    // filteredItems = useMemo(() => {
    //     if (this.state.searchText) {
    //       return items.filter(item => item.includes(this.state.searchText))
    //     } else {
    //       return items
    //     }
    //   }, [items])
    async componentDidMount() {
        const {
            router: {
                params: { type }
            }
        } = getCurrentInstance()
        this.state.form.card_type = type
        //  this.state.couponStr = COUPON_TYPE[type]
        this.setState({
            couponStr: COUPON_TYPE[type]
        })
        let tempDays = [{ label: '当天生效', value: 0 }]
        for (let i = 1; i <= 90; i++) {
            tempDays.push({ label: i + '天生效', value: i })
        }
        this.state.totalDays[0] = tempDays
        this.setState({
            totalDays: this.state.totalDays
        })
        if (this.state.form.card_type == 'cash') {
            this.formRef.current?.setFieldsValue({ useCondition: '2' })
        }
        this.getMainCategory()
        this.getCategory()
        this.getBrand()
       
    }

    async componentDidShow() {
        console.log('dianwu h5 comonentDidShow...')

    }
    // const [form] = Form.useForm()  
    getMainCategory = async () => {
        const category_data = await api.weapp.main_category()

         this.setState({
            mainCategoryList : transformData(category_data, SELECCAT_MAP)
        })
        // let list22 = this.state.mainCategoryList
        // let eee = { label: '全部', value: '' }
        // // list.push(eee)
        // let list = []
        // let rrr = []
        //  list22.forEach((item) => {
        //     if (item.children) {
        //         rrr = item.children
        //         rrr.unshift(eee)
        //         item.children = rrr
        //         item.children.forEach((element) => {
        //             if (element.children) {
        //                 rrr = element.children
        //                 rrr.unshift(eee)
        //                 element.children = rrr
        //             }
        //         });

        //     }
        //    list.push(item)
        // })
        // console.log(list)

    }

    getCategory =  async() => {
        let { distributor_id } = this.props.planSelection
        const { list } = await api.weapp.getTagList({
            distributor_id
        })
        console.log(list)
         this.setState({
            categoryList : transformData(list, TAG_MAP)
        })
    }

    getBrand = async () => {
        const { list } = await api.weapp.brand()
         this.setState({
           brandList : transformData(list, BRAND_MAP2)
        })
    }
    getGood(value) {
        let list = this.transformData(value, GOOD_MAP)
        return list
    }
    transformData(data, obj) {
        let list = []
        data.forEach((item) => {
            item = JSON.parse(item)
            let currentItem = {}
            for (let key in obj) {
                currentItem[obj[key]] = item[key]
            }
            if (item.children) {
                currentItem.children = transformData(item.children, obj)
            }
            list.push(currentItem)
        })
        return list
    }
    categoryToStr = (arr) => {
        const list = []
        arr.forEach(element => {
            if (element?.label?.length > 0) {
                if (element.label != '全部') {
                    list.push(element.label)
                }
            }
        });
        console.log(list)
        return list.join('-')
    }
    onSubmit = async () => {

        const values = this.formRef.current?.getFieldsValue()
        // Dialog.alert({
        //     content: <pre>{JSON.stringify(values, null, 2)}</pre>,
        // })
        console.log(values.begin_time, dayjs(values.begin_time))
        let ddd = new Date(dayjs(values.begin_time)).getTime()
        // new Date(ddd).getTime()
        console.log(timestampToTime(ddd / 1000))
        let params = this.state.form

        console.log(params)
        params = {
            ...params,
            ...JSON.parse(JSON.stringify(values)),

        }

        if (params.item_category.length > 0) {
            let arr = []
            params.item_category.forEach(element => {
                if (element && element.length > 0) {
                    arr.push(element)
                }
            });
            params.item_category = arr
        }
        params.tag_list = null //不需要回传的参数
        params.rel_tag_ids = null //不需要回传的参数
        params.rel_brand_ids = null //不需要回传的参数
        params.brand_list = null //不需要回传的参数
        params.tag_ids = JSON.stringify(params.tag_ids)
        params.rel_item_ids = JSON.stringify(params.rel_item_ids)
        params.brand_ids = JSON.stringify(params.brand_ids)
        params.item_category = JSON.stringify(params.item_category)
        params.itemTreeLists = []

        console.log(params)

        //   params.rel_distributor_ids = JSON.stringify(this.form.rel_distributor_ids)
        //   params.rel_shops_ids = JSON.stringify(this.form.rel_shops_ids)
        params.distributor_info = []
        // params.card_type = 'discount'
        // params.color = '#000000'
        // params.use_all_shops = true
        // params.card_id = ''
        if (params.date_type == 'DATE_TYPE_FIX_TIME_RANGE') {
            params.begin_time = new Date(dayjs(params.begin_time)).getTime() / 1000
            params.end_time = new Date(dayjs(params.end_time)).getTime() / 1000
        } else if (params.date_type === 'DATE_TYPE_FIX_TERM') {
            // DATE_TYPE_FIX_TERM
            params.begin_time = params.be_time[0]
            params.end_time = new Date(dayjs(params.en_time)).getTime() / 1000
        } else if (params.date_type === 'DATE_TYPE_LONG') {
            params.send_begin_time = new Date(dayjs(params.begintime)).getTime() / 1000
            params.begin_time = params.limit[0]
            params.limit = params.limit[0]
        } else {
            params.send_begin_time = new Date(dayjs(params.send_begin_time)).getTime() / 1000
            params.send_end_time = new Date(dayjs(params.send_end_time)).getTime() / 1000
            params.begin_time = new Date(dayjs(params.begin_time)).getTime() / 1000
            params.end_time = new Date(dayjs(params.end_time)).getTime() / 1000
        }

        if (params.card_type == 'new_gift') {
            let { distributor_id } = this.props.planSelection
            params.distributor_ids = JSON.stringify([distributor_id])
            // params.items  = JSON.stringify([])

            // let lll  = list.map((value) =>{
            //     return value.value
            // })
            // params.items = lll
        }
        // 判断使用条件-是否不限额度
        if (params.useCondition === 1) {
            params.least_cost = 0
            params.most_cost = 999999
        }

        // Dialog.alert({
        //     content: <pre>{JSON.stringify(params, null, 2)}</pre>,
        // })
        await api.coupon.creatCoupon(params)

        Taro.navigateBack()
    }
    onFinish = (values) => {
        console.log(values)
        if (values.quantity) {

        }
        this.onSubmit(values)
    }
    onFinishFailed = (values) => {
        // Dialog.alert({
        //     content: <pre>{JSON.stringify(values, null, 2)}</pre>,
        // })
    }
    onClickGoogs = async (values) => {
        console.log('index-294打印values', values)
        let list = this.getGood(values)
        console.log('index-294打印values', list)
        this.state.form.items = values
     this.setState({
            goodsList: list,
            form: this.state.form
        })
        let lll = list.map((value) => {
            return value.value
        })
        // params.items = lll
        this.formRef.current?.setFieldsValue({ rel_item_ids: lll })
    }
    render() {
        const { card_type, items } = this.state.form
        const { selected } = this.state.selected
        return (
            <View className='creat-form'>
                <SpNavBar title={this.state.couponStr} />
                <Form
                    ref={this.formRef}
                    layout='horizontal'
                    footer={
                        <Button block type='submit' color='primary' size='large' >
                            提交
                        </Button>
                    }
                    onFinish={this.onFinish}
                    onFinishFailed={this.onFinishFailed}
                    initialValues={{
                        quantity: 1,
                        get_limit: 1,
                        most_cost: 9999,
                        days: 1,
                        use_all_items: 'true',
                        useCondition: '',
                        lock_time: 1,
                        receive: true,
                        items: '选择商品',
                    }}
                >
                    <Form.Header>基础信息</Form.Header>
                    <Form.Item label='券名称' name='title'
                        rules={[{ required: true, max: 9, message: '字数上限为9个汉字' }]}
                    >
                        <Input placeholder='字数上线为9个汉字' />
                    </Form.Item>
                    {card_type == 'cash' && (
                        <Form.Item
                            name='reduce_cost'
                            label='减免金额(元)'
                            rules={[{
                                required: true,
                                message: '大于0的数',
                                pattern: '([1-9]\\d*(\\.\\d*[1-9])?)|(0\\.\\d*[1-9])'
                            }]}
                        >
                            <Input onChange={console.log} placeholder='大于0的数' />
                        </Form.Item>

                    )}
                    {card_type == 'discount' && (<Form.Item
                        name='discount'
                        label='折扣额度'
                        rules={[{
                            required: true,
                            message: '折扣额度为0-10之间的数字，精确到小数点后1位',
                            pattern: '(^[1-9]{1,1}$)|(^[0-9]{1,2}[\.]{1}[0-9]{1,1}$)'
                        }]}
                    >
                        {/* <Stepper min={1} max={9.9}/> */}
                        <Input onChange={console.log} placeholder='1~10的数字
' />
                    </Form.Item>)}
                    <Form.Item name='quantity' label='发放数量' childElementPosition='left'
                        rules={[{ required: true, type: 'number', message: '字数上限为9个汉字' }]}>
                        <Stepper min={1} />
                    </Form.Item>


                    {(card_type == 'discount') && (<Form.Item name='useCondition' label='使用条件'
                        rules={[{ required: true, message: '请选择使用条件' }]}>
                        <Radio.Group>
                            <Space>
                                <Radio value='1'>不限制</Radio>
                                <Radio value='2'>限制</Radio>
                            </Space>
                        </Radio.Group>
                    </Form.Item>)}
                    <Form.Subscribe to={['useCondition']}>
                        {({ useCondition }) => (
                            <>
                                {useCondition === '2' && (
                                    <>
                                        <Form.Item label="最低可用(元)" name='least_cost'
                                            rules={[{ required: true, message: '最低可用金额不能为空' }]}
                                        >
                                            <Input placeholder='满多少元可用,请输入金额' />
                                        </Form.Item>
                                        {card_type == 'discount' && (<Form.Item label="最高限额(元)" name='most_cost'
                                            rules={[{ required: true, message: '最高限额不能为空' }]}
                                        >
                                            <Input placeholder='99999' />
                                        </Form.Item>)}
                                    </>

                                )}
                            </>
                        )}
                    </Form.Subscribe>

                    {(card_type == 'cash') && (
                        <Form.Item label="最低可用(元)" name='least_cost'
                            rules={[{ required: true, message: '最低可用金额不能为空' }]}
                        >
                            <Input placeholder='满多少元可用,请输入金额' />
                        </Form.Item>)}
                    <Form.Item name='date_type' label='有效期'
                        rules={[{ required: true, message: '请选择有效期' }]}
                    >
                        <Radio.Group>
                            {(card_type == 'cash' || card_type == 'discount') && (<Space direction='vertical'>
                                <Radio value='DATE_TYPE_FIX_TIME_RANGE'>固定日期</Radio>
                                <Radio value='DATE_TYPE_FIX_TERM'>不固定日期</Radio>
                            </Space>)}
                            {(card_type == 'new_gift') && (<Space direction='vertical'>
                                <Radio value='DATE_TYPE_LONG'>长期活动</Radio>
                                <Radio value='DATE_TYPE_SHORT'>短期活动</Radio>
                            </Space>)}
                        </Radio.Group>
                    </Form.Item>
                    <Form.Subscribe to={['date_type']}>
                        {({ date_type }) => (
                            <>
                                {date_type === 'DATE_TYPE_FIX_TIME_RANGE' && (
                                    <>
                                        <Form.Item label="有效开始时间" name='begin_time'
                                            trigger='onConfirm'
                                            rules={[{ required: true, message: '开始时间不能为空' }]}
                                            onClick={(e, datePickerRef) => {
                                                datePickerRef.current?.open() // ⬅️
                                            }}
                                        >
                                            <DatePicker
                                                precision='second'
                                            >
                                                {value =>
                                                    value ? dayjs(value).format('YYYY-MM-DD hh:mm:ss') : '请选择开始时间'
                                                }
                                            </DatePicker>
                                        </Form.Item>
                                        <Form.Item label="有效结束时间" name='end_time'
                                            trigger='onConfirm'
                                            rules={[{ required: true, message: '结束时间不能为空' }]}
                                            onClick={(e, datePickerRef) => {
                                                datePickerRef.current?.open() // ⬅️
                                            }}
                                        >
                                            <DatePicker
                                                precision='second'
                                            >
                                                {value =>
                                                    value ? dayjs(value).format('YYYY-MM-DD hh:mm:ss') : '请选择结束时间'
                                                }
                                            </DatePicker>
                                        </Form.Item>
                                    </>

                                )}
                                {date_type === 'DATE_TYPE_FIX_TERM' && (
                                    <>
                                        <Form.Item label="领取后" name='be_time'
                                            trigger='onConfirm'
                                            rules={[{ required: true, message: '生效时间不能为空' }]}
                                            onClick={(e, datePickerRef) => {
                                                datePickerRef.current?.open() // ⬅️
                                            }}
                                        >
                                            <Picker
                                                columns={this.state.totalDays}>
                                                {value => value.length > 0 ? value[0].label : '请选择生效时间'
                                                    //    console.log(value)
                                                }
                                            </Picker>
                                        </Form.Item>
                                        <Form.Item label="有效天数" name='days'
                                            rules={[{ required: true, type: 'number', message: '有效天数不能为空' }]}
                                        >
                                            <Stepper min={1} />
                                        </Form.Item>
                                        <Form.Item label="统一过期时间" name='en_time'
                                            trigger='onConfirm'
                                            rules={[{ required: true, message: '结束时间不能为空' }]}
                                            onClick={(e, datePickerRef) => {
                                                datePickerRef.current?.open() // ⬅️
                                            }}
                                        >
                                            <DatePicker
                                                precision='second'
                                            >
                                                {value =>
                                                    value ? dayjs(value).format('YYYY-MM-DD hh:mm:ss') : '请选择时间'
                                                }
                                            </DatePicker>
                                        </Form.Item>
                                    </>
                                )}
                                {date_type === 'DATE_TYPE_LONG' && (
                                    <>
                                        <Form.Item label="开始时间" name='begintime'
                                            trigger='onConfirm'
                                            rules={[{ required: true, message: '开始时间不能为空' }]}
                                            onClick={(e, datePickerRef) => {
                                                datePickerRef.current?.open() // ⬅️
                                            }}
                                        >
                                            <DatePicker
                                                precision='second'
                                            >
                                                {value =>
                                                    value ? dayjs(value).format('YYYY-MM-DD hh:mm:ss') : '请选择开始时间'
                                                }
                                            </DatePicker>
                                        </Form.Item>
                                        <Form.Item label="领取后" name='limit'
                                            trigger='onConfirm'
                                            rules={[{ required: true, message: '生效时间不能为空' }]}
                                            onClick={(e, datePickerRef) => {
                                                datePickerRef.current?.open() // ⬅️
                                            }}
                                        >
                                            <Picker
                                                columns={this.state.totalDays}>
                                                {value => value.length > 0 ? value[0].label : '请选择生效时间'
                                                    //    console.log(value)
                                                }
                                            </Picker>
                                        </Form.Item>
                                        <Form.Item label="有效天数" name='days'
                                            rules={[{ required: true, type: 'number', message: '有效天数不能为空' }]}
                                        >
                                            <Stepper min={1} />
                                        </Form.Item>


                                    </>

                                )}
                                {date_type === 'DATE_TYPE_SHORT' && (
                                    <>
                                        <Form.Item label="发放开始时间" name='send_begin_time'
                                            trigger='onConfirm'
                                            rules={[{ required: true, message: '发放开始不能为空' }]}
                                            onClick={(e, datePickerRef) => {
                                                datePickerRef.current?.open() // ⬅️
                                            }}
                                        >
                                            <DatePicker
                                                precision='second'
                                            >
                                                {value =>
                                                    value ? dayjs(value).format('YYYY-MM-DD hh:mm:ss') : '请选择开始时间'
                                                }
                                            </DatePicker>
                                        </Form.Item>
                                        <Form.Item label="发放结束时间" name='send_end_time'
                                            trigger='onConfirm'
                                            rules={[{ required: true, message: '发放结束时间不能为空' }]}
                                            onClick={(e, datePickerRef) => {
                                                datePickerRef.current?.open() // ⬅️
                                            }}
                                        >
                                            <DatePicker
                                                precision='second'
                                            >
                                                {value =>
                                                    value ? dayjs(value).format('YYYY-MM-DD hh:mm:ss') : '请选择结束时间'
                                                }
                                            </DatePicker>
                                        </Form.Item>
                                        <Form.Item label="使用开始时间" name='begin_time'
                                            trigger='onConfirm'
                                            rules={[{ required: true, message: '使用开始不能为空' }]}
                                            onClick={(e, datePickerRef) => {
                                                datePickerRef.current?.open() // ⬅️
                                            }}
                                        >
                                            <DatePicker
                                                precision='second'
                                            >
                                                {value =>
                                                    value ? dayjs(value).format('YYYY-MM-DD hh:mm:ss') : '请选择开始时间'
                                                }
                                            </DatePicker>
                                        </Form.Item>
                                        <Form.Item label="使用结束时间" name='end_time'
                                            trigger='onConfirm'
                                            rules={[{ required: true, message: '使用结束时间不能为空' }]}
                                            onClick={(e, datePickerRef) => {
                                                datePickerRef.current?.open() // ⬅️
                                            }}
                                        >
                                            <DatePicker
                                                precision='second'
                                            >
                                                {value =>
                                                    value ? dayjs(value).format('YYYY-MM-DD hh:mm:ss') : '请选择结束时间'
                                                }
                                            </DatePicker>
                                        </Form.Item>
                                    </>

                                )}

                            </>
                        )}
                    </Form.Subscribe>
                    <Form.Item name='description' label='卡券使用说明'
                        rules={[{ required: true, message: '卡券使用说明不能为空' }]}>
                        <TextArea
                            placeholder='请填写使用本优惠券的注意事项'
                            maxLength={300}
                            showCount
                        />
                    </Form.Item>

                    <Form.Header>适用规则</Form.Header>
                    <Form.Item
                        name='receive'
                        label='前台可直接领取'
                        help='开启后用户可在卡券列表中领取，未开启需手动发放。'
                    >
                        <Switch defaultChecked />
                    </Form.Item>
                    <Form.Item name='get_limit' label='领券限制(张)' childElementPosition='left'
                        rules={[{ required: true, type: 'number', message: '领券限制不能为空' }]}>
                        <Stepper min={1} />
                    </Form.Item>
                    <Form.Header>商品</Form.Header>
                    {card_type == 'new_gift' && (<><Form.Header>兑换规则</Form.Header>
                        <Form.Item name='lock_time' label='选定商品锁定时间(小时)' help='消费者使用兑换券选定商品后，为避免到店后无兑换商品，则该商品对应库存锁定时间，时间需大于0，且为整数'
                            rules={[{ required: true, type: 'number', message: '锁定时间不能为空' }]}>
                            <Stepper min={1} />
                        </Form.Item></>)}
                    {card_type != 'new_gift' && (<Form.Item name='use_all_items' label='适用商品' required>
                        <Radio.Group  >
                            <Space direction='vertical'>
                                <Radio value='true'>全部商品使用</Radio>
                                <Radio value='false'>指定商品使用</Radio>
                                <Radio value='category'>指定管理分类适用</Radio>
                                <Radio value='tag'>指定商品标签适用</Radio>
                                <Radio value='brand'>指定品牌适用</Radio>
                            </Space>
                        </Radio.Group>
                    </Form.Item>)}
                    {card_type == 'new_gift' && (
                        <Form.Item label="指定商品" name='rel_item_ids'
                            trigger='onConfirm'
                            rules={[{ required: true, message: '商品不能为空' }]}
                            onClick={(e) => {
                                this.setState({
                                    visible: true
                                })
                            }}
                        >
                            {/* <Input readOnly /> */}
                            <Selector
                                columns={2}
                                multiple
                                options={this.state.goodsList}
                                disabled
                            />
                        </Form.Item>)}
                    <Form.Subscribe to={['use_all_items']}>
                        {({ use_all_items }) => (
                            <>
                                {use_all_items === 'false' && (
                                    <>
                                        <Form.Item label="指定商品" name='rel_item_ids'
                                            trigger='onConfirm'
                                            rules={[{ required: true, message: '商品不能为空' }]}
                                            onClick={(e) => {
                                                this.setState({
                                                    visible: true
                                                })
                                            }}
                                        >
                                            {/* <Input readOnly /> */}
                                            <Selector
                                                columns={2}
                                                multiple
                                                options={this.state.goodsList}
                                                disabled
                                            />
                                        </Form.Item>
                                    </>
                                )}
                                {use_all_items === 'category' && (
                                    <>
                                        <Form.Item label="管理分类" name='item_category'
                                            trigger='onConfirm'
                                            rules={[{ required: true, message: '管理分类不能为空' }]}
                                            onClick={(e, datePickerRef) => {
                                                datePickerRef.current?.open() // ⬅️
                                            }}
                                        >
                                            <CascadePicker
                                                options={this.state.mainCategoryList}
                                            >
                                                {value =>
                                                    value.length > 0 ? this.categoryToStr(value) : '请选择管理分类'

                                                }
                                            </CascadePicker >
                                        </Form.Item>
                                    </>
                                )}
                                {use_all_items === 'tag' && (
                                    <>
                                        <Form.Item name='tag_ids' label='商品标签'>
                                            <Selector
                                                columns={3}
                                                multiple
                                                options={this.state.categoryList}
                                            />
                                        </Form.Item>
                                    </>

                                )}
                                {use_all_items === 'brand' && (
                                    <>
                                        <Form.Item name='brand_ids' label='商品品牌'>
                                            <Selector
                                                columns={3}
                                                multiple
                                                options={this.state.brandList}
                                            />
                                        </Form.Item>
                                    </>

                                )}

                            </>
                        )}
                    </Form.Subscribe>
                </Form>
                <Popup
                    position='right'
                    showCloseButton
                    visible={this.state.visible}
                    onMaskClick={() => {
                        this.setState({
                            visible: false
                        })
                    }}
                    destroyOnClose
                    onClose={() => {
                        this.setState({
                            visible: false,
                        })
                    }}
                >
                    <div className='rigth-btn' onClick={() => {
                        this.setState({
                            visible: false,
                        })
                    }}>
                        确定
                    </div>
                    <div className='popup-body'>
                        <div >
                            <GoodsCheck onChange={this.onClickGoogs} selected={items} value='1'></GoodsCheck>
                        </div>
                    </div>
                </Popup>
            </View >

        )
    }
}
